package icu.zqyhdm.commonService.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import icu.zqyhdm.commonService.service.OssService;
import icu.zqyhdm.commonService.utils.ConstantOssPropertiesUtils;
import icu.zqyhdm.helper.JwtHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Description
 * @Author lifu
 * @Date 2021/7/9 20:47
 */
@Service
public class OssServiceImpl implements OssService {

    /**
     * 上传文件到阿里云oss
     */
    @Override
    public String upload(MultipartFile multipartFile,String fileUrl) {
        String endpoint = ConstantOssPropertiesUtils.ENDPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.SECRECT;
        String bucketName = ConstantOssPropertiesUtils.BUCKET;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject(bucketName, fileUrl ,inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        //返回上传后的路径
        String url = "https://"+bucketName+"."+endpoint+"/"+fileUrl;
        return url;
    }
}
